import { useState } from './useState';

/**
 * 倒计时
 *
 * @returns {[number, Function, Function]} [timer, onStart, onStop]
 */
export function useTimerInterval() {
  const [timer, setTimer] = useState(0);
  let interval = null;

  /**
   * 开始倒计时
   *
   * @param timer 倒计时时间
   * @returns Object {interval}
   */
  const onStartTimer = (timer = 60) => {
    onStopTimer();
    setTimer(timer);
    interval = setInterval(() => {
      setTimer(--timer);
      timer === 0 && clearInterval(interval);
    }, 1000);

    return interval;
  };

  /**
   * 停止倒计时
   * @returns void
   */
  const onStopTimer = () => {
    clearInterval(interval);
    interval === null && setTimer(0);
  };

  return [timer, onStartTimer, onStopTimer];
}
